package wang.luo.clnczjl;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.afollestad.materialdialogs.LayoutMode;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.bottomsheets.BottomSheet;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import okhttp3.Call;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String PREFS_CNS = "myCns";
    /**
     * * 【动态申请SD卡读写的权限】
     * * Android6.0之后系统对权限的管理更加严格了，不但要在AndroidManifest中添加，还要在应用运行的时候动态申请
     * *
     **/
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final String[] PERMISSON_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.INTERNET"};
    public static String myCnsIp = "", myCnsPw = "";
    public static boolean customCnsEn = false;
    private final String MAIN_TAG = "MainActivity";
    private final String ZJLmagiskPath = "/clnc/clnc_magisk/";
    private String deviceInfo = "Linux; " + "Android " + android.os.Build.VERSION.RELEASE + "; " +
            android.os.Build.MODEL + " Build" + "/" + android.os.Build.ID + "; wv";
    private String RemoteVersions = ""; //远程版本
    private String updateContent = ""; //更新内容
    private String RemoteIP = ""; //远程IP
    private String RemoteIpASN = ""; //IP归属地
    private String remoteNotice = "";
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                String LocalVersions = Utils.getVersionName(MainActivity.this);
                BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                dialog.cancelOnTouchOutside(true);
                dialog.title(null, "检测到新版本是否更新？");
                dialog.message(null, "当前版本：" + LocalVersions + "\r\n" + "最新版本：" + RemoteVersions + "\r\n" + updateContent, null);
                dialog.positiveButton(null, "更新", materialDialog -> {
                    String downloadLink = giteeUrl.getremoteurlText();
                    downloadLink = downloadLink.replaceAll("versions", RemoteVersions);
                    Log.d(MAIN_TAG, "downloadLink: " + downloadLink);
                    Uri uri = Uri.parse(downloadLink);
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.setData(uri);
                    startActivity(intent);
                    return null;
                });
                dialog.negativeButton(null, "取消", materialDialog -> {
                    return null;
                });
                dialog.show();
            } else if (msg.what == 200) {
                BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                dialog.cancelOnTouchOutside(true);
                dialog.title(null, "公告：");
                dialog.message(null, remoteNotice, null);
                dialog.negativeButton(null, "确认", materialDialog -> {
                    return null;
                });
                dialog.show();
            } else if (msg.what == 300) {

            }
        }
    };
    private boolean remoteCnsPublic = false;

    public static void verifyStoragePermissions(Activity activity) {
        try {
            if (ActivityCompat.checkSelfPermission(activity, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {/**【判断是否已经授予权限】**/
                ActivityCompat.requestPermissions(activity, PERMISSON_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
            if (ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {/**【判断是否已经授予权限】**/
                ActivityCompat.requestPermissions(activity, PERMISSON_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
            if (ActivityCompat.checkSelfPermission(activity, "android.permission.INTERNET") != PackageManager.PERMISSION_GRANTED) {/**【判断是否已经授予权限】**/
                ActivityCompat.requestPermissions(activity, PERMISSON_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //检测root权限
        if (!CommandExecution.getRootAhth()) {
            BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
            MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
            dialog.cancelOnTouchOutside(false);
            dialog.title(null, "未获取ROOT权限");
            dialog.positiveButton(null, "退出", materialDialog -> {
                finish();
                return null;
            });
            dialog.show();
        } else {
            //申请权限
            setContentView(R.layout.activity_main);
        }
        //设备UA
//        deviceInfo = deviceInfo.replaceAll("RK", "SK");
//        Log.d("deviceInfo", deviceInfo);

        SharedPreferences cnsInfo = getSharedPreferences(PREFS_CNS, MODE_PRIVATE);
        customCnsEn = cnsInfo.getBoolean("status", false);//读取age
        myCnsIp = cnsInfo.getString("myCnsIp", null);
        myCnsPw = cnsInfo.getString("myCnsPw", null);

        initMainActivityUI();
    }

    private void initMainActivityUI() {
        Button buttonOpen = findViewById(R.id.button);
        Button buttonClose = findViewById(R.id.buttonClose);
        Button buttonUpdate = findViewById(R.id.buttonUpdate);
        Button buttonInstall = findViewById(R.id.buttonInstall);
        Button buttonDelete = findViewById(R.id.buttonDelete);
        Button buttonIp = findViewById(R.id.buttonIp);
        Button buttonEnData = findViewById(R.id.buttonEnData);
        Button buttonDisEnData = findViewById(R.id.buttonDisenData);
        Button buttonReboot = findViewById(R.id.buttonReboot);
        Button buttonSpeed = findViewById(R.id.buttonSpeed);

        buttonOpen.setOnClickListener(MainActivity.this);
        buttonClose.setOnClickListener(MainActivity.this);
        buttonUpdate.setOnClickListener(MainActivity.this);
        buttonInstall.setOnClickListener(MainActivity.this);
        buttonDelete.setOnClickListener(MainActivity.this);
        buttonIp.setOnClickListener(MainActivity.this);
        buttonEnData.setOnClickListener(MainActivity.this);
        buttonDisEnData.setOnClickListener(MainActivity.this);
        buttonReboot.setOnClickListener(MainActivity.this);
        buttonSpeed.setOnClickListener(MainActivity.this);

        decompressResourceFiles();

        getRemoteInformation(giteeUrl.getConf());

        verifyStoragePermissions(MainActivity.this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                CommandExecution.CommandResult openResult = CommandExecution.execCommand("/data/防跳/clnc_magisk/开启.sh\n", true);
                if (openResult.errorMsg.contains("inaccessible or not found")) {
                    BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                    MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                    dialog.message(null, "未找到脚本，请确认是否安装过脚本！", null);
                    dialog.negativeButton(null, "确认", materialDialog -> {
                        return null;
                    });
                    dialog.show();
                } else if (openResult.successMsg.contains("正在运行")) {
                    BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                    MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                    dialog.title(null, "执行成功");
                    String successMsg = "";
                    try {
                        successMsg += "模式：" + Utils.extractSubstring(openResult.successMsg, "模式 ", "✄┄") + "\n";
                        successMsg += Utils.extractSubstring(openResult.successMsg, "正在测试DNS...", "        ") + "\n";
                        successMsg += Utils.extractSubstring(openResult.successMsg, "正在测试HTTP...", "        ") + "\n";
                        successMsg += Utils.extractSubstring(openResult.successMsg, "正在测试HTTPS...", "        ") + "\n";
                        successMsg += Utils.extractSubstring(openResult.successMsg, "正在测试UDP...", "        ") + "\n";
                        successMsg += "当前IP: " + Utils.extractSubstring(openResult.successMsg, "当前IP: ", "归属地:") + "\n";
                        successMsg += "归属地: " + Utils.extractSubstring(openResult.successMsg, "归属地: ", "✄┄") + "\n";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dialog.message(null, successMsg, null);
                    dialog.negativeButton(null, "确认", materialDialog -> {
                        return null;
                    });
                    dialog.show();
                } else {
                    Toast.makeText(MainActivity.this, "脚本执行失败！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonClose:
                CommandExecution.CommandResult closResult = CommandExecution.execCommand("/data/防跳/clnc_magisk/关闭.sh\n", true);
                if (closResult.errorMsg.contains("inaccessible or not found")) {
                    BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                    MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                    dialog.message(null, "未找到脚本，请确认是否安装过脚本！", null);
                    dialog.negativeButton(null, "确认", materialDialog -> {
                        return null;
                    });
                    dialog.show();
                } else if (closResult.successMsg.contains("没有运行")) {
                    BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                    MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                    dialog.title(null, "执行成功");
                    String successMsg = "";
                    try {
                        successMsg += Utils.extractSubstring(closResult.successMsg, "┄× ", "✄┄") + "\n";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dialog.message(null, successMsg, null);
                    dialog.negativeButton(null, "确认", materialDialog -> {
                        return null;
                    });
                    dialog.show();
                } else {
                    Toast.makeText(MainActivity.this, "脚本执行失败！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonIp:
                getIpNetworks();
                break;
            case R.id.buttonEnData:
                int dataEnResult = CommandExecution.execCommand("svc data enable\n", true).result;
                if (dataEnResult == 0 && NetworkUtils.getMobileDataEnabled()) {
                    Toast.makeText(MainActivity.this, "数据流量已开启！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "操作失败！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonDisenData:
                int dataDisResult = CommandExecution.execCommand("svc data disable\n", true).result;
                if (dataDisResult == 0 && !NetworkUtils.getMobileDataEnabled()) {
                    Toast.makeText(MainActivity.this, "数据流量已关闭！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "操作失败！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.buttonUpdate:
                iPUpdate();
                break;
            case R.id.buttonSpeed:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WebActivity.class);
                intent.putExtra("url", "https://mping.chinaz.com/?host=cloudnproxy.baidu.com");
                startActivity(intent);
                break;
            case R.id.buttonInstall:
                installScript();
                break;
            case R.id.buttonDelete:
                deleteScript();
                break;
            case R.id.buttonReboot:
                rebootPhone();
                break;
            default:
                break;
        }
    }

    private void getIpNetworks() {
        String getSuccessMsg = CommandExecution.execCommand("curl cip.cc\n", false).successMsg;
        Log.d("getSuccessMsg", "cip.cc:" + getSuccessMsg);
        if (getSuccessMsg.contains("www.cip.cc")) {
            BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
            MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
            dialog.message(null, getSuccessMsg, null);
            dialog.negativeButton(null, "确认", materialDialog -> {
                return null;
            });
            dialog.show();
        } else {
            String getMyIpSuccessMsg = CommandExecution.execCommand("/\n", false).successMsg;
            if (getMyIpSuccessMsg.contains("来自于")) {
                BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
                MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
                dialog.message(null, getMyIpSuccessMsg, null);
                dialog.negativeButton(null, "确认", materialDialog -> {
                    return null;
                });
                dialog.show();
            } else {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WebActivity.class);
                intent.putExtra("url", "https://m.ip138.com");
                startActivity(intent);
            }
//            Log.d("getSuccessMsg", "cip.cc:" + getSuccessMsg);
//            Intent intent = new Intent();
//            intent.setClass(MainActivity.this, WebActivity.class);
//            intent.putExtra("url", "https://m.ip138.com");
//            startActivity(intent);
        }
    }

    private void iPUpdate() {
        if (RemoteIP.equals("")) {
            getRemoteInformation(giteeUrl.getConf());
        }
        String Command = null;
        try {
            Command = "cp -r " + "/data/防跳/clnc_magisk/clnc_bd.conf " + getDiskCacheDir() + ZJLmagiskPath + "\n";
        } catch (IOException e) {
            e.printStackTrace();
        }
        String getCommandresult = "";
        getCommandresult = CommandExecution.execCommand(Command, true).errorMsg;
        if (getCommandresult.contains("No such file or directory")) {
            BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
            MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
            dialog.title(null, "未安装脚本！");
            dialog.negativeButton(null, "确认", materialDialog -> {
                return null;
            });
            dialog.show();
            return;
        }
        String Path = "";
        try {
            Path = getDiskCacheDir() + ZJLmagiskPath + "clnc_bd.conf";
        } catch (IOException e) {
            e.printStackTrace();
        }
        String conf = Utils.readFileSdcard(Path);
        Log.d("conf:", conf);//readFileSdcard(Path)
        String getLocalIP = Utils.extractSubstring(conf, "iP = ", ":443;");
        Log.d("getLocalIP:", getLocalIP);

        BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
        MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
        if (RemoteIP.equals("")) {
            dialog.title(null, "远程IP获取失败！");
            dialog.positiveButton(null, "确认", materialDialog -> {
                getRemoteInformation(giteeUrl.getConf());
                return null;
            });
        } else {
            dialog.title(null, "确认更换IP？");
            dialog.message(null, "本地IP：" + getLocalIP + "\r\n" +
                            "远程IP：" + RemoteIP + "\r\n" +
                            "远程IP归属地：" + RemoteIpASN + "\r\n" +
                            "更新后需要重新开启脚本！"
                    , null);
            dialog.positiveButton(null, "确认", materialDialog -> {
                String dataPath = "";
                try {
                    dataPath = getDiskCacheDir() + ZJLmagiskPath + "clnc_bd.conf";
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String result = conf.replaceAll(getLocalIP, RemoteIP);
                Log.d("result:", result);//readFileSdcard(Path)
                Utils.writeFileSdcard(dataPath, result);

                String CommandCP = "cp -r " + dataPath + " /data/防跳/clnc_magisk" + "\n";
                Log.d("lwang:", CommandCP);
                CommandExecution.execCommand(CommandCP, true);
                CommandExecution.execCommand("chmod -R 777 /data/防跳/clnc_magisk\n", true);

                CommandCP = "cp -r " + dataPath + " /data/adb/modules/clnc/clnc_magisk" + "\n";
                Log.d("lwang:", CommandCP);
                CommandExecution.execCommand(CommandCP, true);
                CommandExecution.execCommand("chmod -R 777 /data/adb/modules" + ZJLmagiskPath + "clnc_bd.conf\n", true);
                return null;
            });
        }
        dialog.negativeButton(null, "取消", materialDialog -> {
            return null;
        });
        dialog.neutralButton(null, "自定义", materialDialog -> {
            String pingIp = CommandExecution.execCommand("ping -c 1 cloudnproxy.baidu.com", true).successMsg;
            String autoIp = Utils.extractSubstring(pingIp, "bytes from ", ": icmp_seq");
            Log.d("autoIp:", autoIp);
            /*@setView 装入一个EditView
             */
            final EditText editText = new EditText(MainActivity.this);
            editText.setText(autoIp);
            AlertDialog.Builder inputDialog =
                    new AlertDialog.Builder(MainActivity.this);
            inputDialog.setTitle("请输入IP：").setView(editText);
            inputDialog.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
            inputDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!RegexUtils.isIP(editText.getText().toString())) {
                                Toast.makeText(MainActivity.this, "请输入正确IP", Toast.LENGTH_SHORT).show();
                            } else {
                                String Path = "";
                                try {
                                    Path = getDiskCacheDir() + ZJLmagiskPath + "clnc_bd.conf";
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                String result = conf.replaceAll(getLocalIP, editText.getText().toString());
                                Log.d("result:", result);//readFileSdcard(Path)
                                Utils.writeFileSdcard(Path, result);

                                String Command = "cp -r " + Path + " /data/防跳/clnc_magisk" + "\n";
                                Log.d("lwang:", Command);
                                CommandExecution.execCommand(Command, true);
                                CommandExecution.execCommand("chmod -R 777 /data/防跳/clnc_magisk\n", true);

                                Command = "cp -r " + Path + " /data/adb/modules/clnc/clnc_magisk" + "\n";
                                Log.d("lwang:", Command);
                                CommandExecution.execCommand(Command, true);
                                CommandExecution.execCommand("chmod -R 777 /data/adb/modules" + ZJLmagiskPath + "clnc_bd.conf\n", true);
                            }

                        }
                    }).show();
            return null;
        });
        dialog.show();
    }

    private void installScript() {
        decompressResourceFiles();
        CommandExecution.execCommand("rm -rf /data/ZJL2.0_magisk\n", true);
        CommandExecution.execCommand("rm -rf /data/adb/modules/ZJLPreventNetworkTrafficDeductionScript\n", true);
        BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
        MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
        dialog.title(null, "确认安装脚本？");
        dialog.message(null, "如果已安装过脚本，则会覆盖安装。\r\n安装后如果需要Magisk生效，需要重启手机。", null);
        dialog.positiveButton(null, "确认", materialDialog -> {
            String Path = "";
            try {
//                Path = getDiskCacheDir() + "/ZJLPreventNetworkTrafficDeductionScript/ZJL2.0_magisk";
                Path = getDiskCacheDir() + "/clnc/clnc_magisk";
            } catch (IOException e) {
                e.printStackTrace();
            }
            String Command = "cp -r " + Path + " /data/防跳" + "\n";
            Log.d("lwang:", Command);
            CommandExecution.execCommand(Command, true);
            CommandExecution.execCommand("chmod -R 777 /data/防跳\n", true);

            String magiskPath = "";
            try {
                Path = getDiskCacheDir() + "/clnc";
            } catch (IOException e) {
                e.printStackTrace();
            }
            Command = "cp -r " + Path + " /data/adb/modules" + "\n";
            Log.d("lwang:", Command);
            CommandExecution.execCommand(Command, true);
            CommandExecution.execCommand("chmod -R 777 /data/adb/modules/clnc\n", true);
//            Toast.makeText(MainActivity.this, "安装完成，请手动重启手机！", Toast.LENGTH_SHORT).show();
            return null;
        });
        dialog.negativeButton(null, "取消", materialDialog -> {
            return null;
        });
        dialog.show();
    }

//    private void installScript(boolean isQuiesce) {
//        decompressResourceFiles();
//        CommandExecution.execCommand("rm -rf /data/ZJL2.0_magisk\n", true);
//        CommandExecution.execCommand("rm -rf /data/adb/modules/ZJLPreventNetworkTrafficDeductionScript\n", true);
//        if (!isQuiesce) {
//            BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
//            MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
//            dialog.title(null, "确认安装脚本？");
//            dialog.message(null, "如果已安装过脚本，则会覆盖安装。\r\n安装后如果需要Magisk生效，需要重启手机。", null);
//            dialog.positiveButton(null, "确认", materialDialog -> {
//                String Path = "";
//                try {
//                    Path = getDiskCacheDir() + "/ZJLPreventNetworkTrafficDeductionScript/ZJL2.0_magisk";
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                String Command = "cp -r " + Path + " /data" + "\n";
//                Log.d("lwang:", Command);
//                CommandExecution.execCommand(Command, true);
//                CommandExecution.execCommand("chmod -R 777 /data/ZJL2.0_magisk\n", true);
//
//                String magiskPath = "";
//                try {
//                    Path = getDiskCacheDir() + "/ZJLPreventNetworkTrafficDeductionScript";
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                Command = "cp -r " + Path + " /data/adb/modules" + "\n";
//                Log.d("lwang:", Command);
//                CommandExecution.execCommand(Command, true);
//                CommandExecution.execCommand("chmod -R 777 /data/adb/modules/ZJLPreventNetworkTrafficDeductionScript\n", true);
////                Toast.makeText(MainActivity.this, "安装完成，请手动重启手机！", Toast.LENGTH_SHORT).show();
//                return null;
//            });
//            dialog.negativeButton(null, "取消", materialDialog -> {
//                return null;
//            });
//            dialog.show();
//        } else {
//            String Path = "";
//            try {
//                Path = getDiskCacheDir() + "/ZJLPreventNetworkTrafficDeductionScript/ZJL2.0_magisk";
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            String Command = "cp -r " + Path + " /data" + "\n";
//            Log.d("lwang:", Command);
//            CommandExecution.execCommand(Command, true);
//            CommandExecution.execCommand("chmod -R 777 /data/ZJL2.0_magisk\n", true);
//
//            String magiskPath = "";
//            try {
//                Path = getDiskCacheDir() + "/ZJLPreventNetworkTrafficDeductionScript";
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Command = "cp -r " + Path + " /data/adb/modules" + "\n";
//            Log.d("lwang:", Command);
//            CommandExecution.execCommand(Command, true);
//            CommandExecution.execCommand("chmod -R 777 /data/adb/modules/ZJLPreventNetworkTrafficDeductionScript\n", true);
//            Toast.makeText(MainActivity.this, "安装完成，请手动重启手机！", Toast.LENGTH_SHORT).show();
//        }
//    }

    private void deleteScript() {
        BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
        MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
        dialog.title(null, "确认删除脚本？");
        dialog.positiveButton(null, "确认", materialDialog -> {
            CommandExecution.execCommand("rm -rf /data/防跳/clnc_magisk\n", true);
            CommandExecution.execCommand("rm -rf /data/adb/modules/clnc\n", true);
            Toast.makeText(MainActivity.this, "删除完成，请手动重启手机！", Toast.LENGTH_SHORT).show();
            return null;
        });
        dialog.negativeButton(null, "取消", materialDialog -> {
            return null;
        });
        dialog.show();
    }

    private void rebootPhone() {
        BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
        MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
        dialog.title(null, "确认重启手机？");
        dialog.positiveButton(null, "确认", materialDialog -> {
            CommandExecution.execCommand("reboot\n", true);
            return null;
        });
        dialog.negativeButton(null, "取消", materialDialog -> {
            return null;
        });
        dialog.show();
    }

//    private void setCns(String cnsIP, String cnsPw, boolean isOpen) {
//        if (RegexUtils.isIP(cnsIP)) {
//            myCnsPw = cnsIP;
//            myCnsIp = cnsPw;
//            customCnsEn = isOpen;
//            SharedPreferences cnsInfo = getSharedPreferences(PREFS_CNS, MODE_PRIVATE);
//            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = cnsInfo.edit();//获取Editor
//            editor.putBoolean("status", customCnsEn);
//            editor.putString("myCnsIp", myCnsIp);
//            editor.putString("myCnsPw", myCnsPw);
//            editor.apply();
//            installScript(true);
//        }
//    }

    private void getRemoteInformation(String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(MAIN_TAG, url);
                HttpUtil.sendRequestWithOkhttp(url, new okhttp3.Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        assert response.body() != null;
                        String result = response.body().string();
                        Log.d(MAIN_TAG, "" + result + ", isJson:" + JsonUtils.isGoodJson(result));
                        if (JsonUtils.isGoodJson(result)) {
                            Gson gson = new Gson();
                            Json json = gson.fromJson(result, Json.class);
                            RemoteVersions = json.getVersion();
                            updateContent = json.getInfo();
                            remoteCnsPublic = json.getCNSPUBLIC() != 0;
                            if (!customCnsEn && remoteCnsPublic) {
                                myCnsPw = json.getCNSPASSW();
                                myCnsIp = json.getCNSIP();
                            }
                            RemoteIP = json.getIp();
                            RemoteIpASN = json.getASN();
                            remoteNotice = json.getNotice();
                            Log.d(MAIN_TAG, "RemoteVersions:" + RemoteVersions);
                            Log.d(MAIN_TAG, updateContent);
                            if (!RemoteVersions.equals("")) {
                                if (!Utils.getVersionName(MainActivity.this).equals(RemoteVersions)) {
                                    mHandler.sendEmptyMessage(100);
                                }
                            }
                            if (json.getnoticeEN() == 1 && !remoteNotice.equals("")) {
                                mHandler.sendEmptyMessage(200);
                            }
                        }
                    }
                });
            }
        }).start();
    }

    public String getDiskCacheDir() throws IOException {
        File cachePath = null;
        cachePath = this.getExternalFilesDir(null);
        return "" + cachePath;
    }

    private void doCopyFile() throws IOException {
        File externalDir = this.getExternalFilesDir(null);
//        Utils.doCopy(this, "ZJL2.0_magisk", externalDir.getPath());
        Utils.doCopy(this, "clnc", externalDir.getPath());
    }

    private void decompressResourceFiles() {
        new Thread() {
            @Override
            public void run() {
                try {
                    CommandExecution.execCommand("rm -rf " + getDiskCacheDir() + "\n", true);
                    doCopyFile();
                    String cnsIp = myCnsIp;
                    String cnsPw = myCnsPw;
                    String Path = "";
                    try {
                        Path = getDiskCacheDir() + ZJLmagiskPath + "clnc_bd.conf";
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String conf = Utils.readFileSdcard(Path);
                    Log.d("conf2:", conf);//readFileSdcard(Path)
                    String getLocalCnsIP = Utils.extractSubstring(conf, "cns_server = ", ";\n");
                    Log.d("getLocalCnsIP:", getLocalCnsIP);
                    String getLocalCnsPws = Utils.extractSubstring(conf, "cns_passwd = ", ";\n");
                    Log.d("getLocalCnsPws:", getLocalCnsPws);
                    if (StringUtils.isTrimEmpty(cnsIp)) {
                        cnsIp = "47.92.195.27:443";
                        cnsPw = "3127390";
                    }
                    Log.d(MAIN_TAG, "cnsPw:" + cnsIp + ",cnsPw:" + cnsPw);
                    String confPath = "";
                    try {
                        confPath = getDiskCacheDir() + ZJLmagiskPath + "clnc_bd.conf";
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                    String conf = Utils.readFileSdcard(confPath);
//                    Log.d("conf:", conf);//readFileSdcard(Path)

                    if (customCnsEn || remoteCnsPublic) {
                        String result = "";
                        Log.d(MAIN_TAG, "conf:" + conf);
                        result = conf.replaceAll(getLocalCnsIP, cnsIp).replaceAll(getLocalCnsPws, cnsPw);
                        Log.d(MAIN_TAG, result);//readFileSdcard(Path)
                        Utils.writeFileSdcard(confPath, result);
                    }
//                    Log.d(MAIN_TAG, result);//readFileSdcard(Path)

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater()获得MenuIflater对象，inflate()方法给当前活动创建菜单
        getMenuInflater().inflate(R.menu.main, menu);
        //true 代表允许创建的菜单显示出来
        return true;
    }

    @SuppressLint({"NonConstantResourceId", "ResourceType"})
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.ab_item) {
            BottomSheet bottomSheet = new BottomSheet(LayoutMode.WRAP_CONTENT);
            MaterialDialog dialog = new MaterialDialog(MainActivity.this, bottomSheet);
            dialog.title(null, "关于：");
            dialog.message(null, "版本：" + Utils.getVersionName(MainActivity.this) + "\r\nBy lwang", null);
            dialog.negativeButton(null, "确认", materialDialog -> {
                return null;
            });
            dialog.show();
        } else if (item.getItemId() == R.id.cns_item) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, setCnsActivity.class);
            startActivity(intent);
        }
        return true;
    }
}